package com.journaldev.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.journaldev.spring.model.Medicine;

@Repository
public class MedicineDAOImpl implements MedicineDAO {
	
	private static final Logger logger = LoggerFactory.getLogger(CityDAOImpl.class);

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sf){
		this.sessionFactory = sf;
	}

	@Override
	public void addMedicine(Medicine p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(p);
		logger.info("addMedicine successfully, Medicine Details="+p);
	}

	@Override
	public void updateMedicine(Medicine p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.update(p);
		//session.save(p);
		logger.info("updateMedicine successfully, Medicine Details="+p);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Medicine> listMedicine() {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		List<Medicine> medicineList = session.createQuery("from Medicine").list();
		for(Medicine p : medicineList){
			logger.info("Medicine List::"+p);
		}
		return medicineList;
	}

	@Override
	public Medicine getMedicineById(int id) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();		
		Medicine p = (Medicine) session.get(Medicine.class, new Integer(id));
		logger.info("Medicine loaded successfully, Medicine details="+p);
		return p;
	}

	@Override
	public void removeMedicine(int id) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		Medicine p = (Medicine) session.load(Medicine.class, new Integer(id));
		if(null != p){
			session.delete(p);
		}
		logger.info("Medicine deleted successfully, Medicine details="+p);
	}

}
